import React, { useState, useRef, useMemo } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Slider } from '@/components/ui/slider'
import { Volume2, VolumeX, Play, Pause, Expand, MinusCircle } from 'lucide-react'

export type MediaPreviewTyep = 'video' | 'audio' | 'image'
export const MediaPreviewTyepList = ['video', 'audio', 'image'] as const

interface MediaPreviewProps {
  url: string
  title?: string
  type: MediaPreviewTyep
  onClose?: () => void
  open: boolean
}

const MediaPreview: React.FC<MediaPreviewProps> = ({
  url,
  title,
  type,
  onClose,
  open,
}) => {
  const [isPlaying, setIsPlaying] = useState(false)
  const [isMuted, setIsMuted] = useState(false)
  const [volume, setVolume] = useState(1)
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)
  const mediaRef = useRef<HTMLVideoElement | HTMLAudioElement>(null)

  // 处理播放/暂停
  const handlePlayPause = () => {
    if (mediaRef.current) {
      if (isPlaying) {
        mediaRef.current.pause()
      } else {
        mediaRef.current.play()
      }
      setIsPlaying(!isPlaying)
    }
  }

  // 处理音量变化
  const handleVolumeChange = (value: number[]) => {
    const newVolume = value[0]
    setVolume(newVolume)
    if (mediaRef.current) {
      mediaRef.current.volume = newVolume
    }
  }

  // 处理静音切换
  const handleMuteToggle = () => {
    if (mediaRef.current) {
      mediaRef.current.muted = !isMuted
      setIsMuted(!isMuted)
    }
  }

  // 处理时间更新
  const handleTimeUpdate = () => {
    if (mediaRef.current) {
      setCurrentTime(mediaRef.current.currentTime)
    }
  }

  // 处理加载完成
  const handleLoadedMetadata = () => {
    if (mediaRef.current) {
      setDuration(mediaRef.current.duration)
    }
  }

  // 格式化时间
  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60)
    const seconds = Math.floor(time % 60)
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }

  const dialogTitle = useMemo(() => {
    if (title) {
      return title
    }
    switch (type) {
      case 'video':
        return 'Video Preview'
      case 'audio':
        return 'Audio Preview'
      case 'image':
        return 'Image Preview'
      default:
        return 'Media Preview'
    }
  }, [title, type])

  const renderMedia = () => {
    switch (type) {
      case 'video':
        return (
          <div className="relative max-h-[75vh]">
            <video
              ref={mediaRef as React.RefObject<HTMLVideoElement>}
              src={url}
              className="w-full max-h-[75vh] rounded-lg"
              onTimeUpdate={handleTimeUpdate}
              onLoadedMetadata={handleLoadedMetadata}
              onEnded={() => setIsPlaying(false)}
            />
            {/* 视频控制栏 */}
            <div className="absolute bottom-0 left-0 right-0 bg-black/50 p-4 rounded-b-lg">
              <div className="flex items-center gap-4">
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={handlePlayPause}
                  className="text-white hover:text-white/80"
                >
                  {isPlaying ? <Pause size={20} /> : <Play size={20} />}
                </Button>

                <div className="flex items-center gap-2 text-white text-sm">
                  {formatTime(currentTime)} / {formatTime(duration)}
                </div>

                <div className="flex-1">
                  <Slider
                    value={[currentTime]}
                    min={0}
                    max={duration}
                    step={0.1}
                    onValueChange={(value) => {
                      if (mediaRef.current) {
                        mediaRef.current.currentTime = value[0]
                      }
                    }}
                    className="w-full"
                  />
                </div>

                <div className="flex items-center gap-2">
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={handleMuteToggle}
                    className="text-white hover:text-white/80"
                  >
                    {isMuted ? <VolumeX size={20} /> : <Volume2 size={20} />}
                  </Button>
                  <div className="w-24">
                    <Slider
                      value={[isMuted ? 0 : volume]}
                      min={0}
                      max={1}
                      step={0.1}
                      onValueChange={handleVolumeChange}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        )

      case 'audio':
        return (
          <div className="w-full bg-gray-100 dark:bg-gray-800 rounded-lg p-6">
            <audio
              ref={mediaRef as React.RefObject<HTMLAudioElement>}
              src={url}
              onTimeUpdate={handleTimeUpdate}
              onLoadedMetadata={handleLoadedMetadata}
              onEnded={() => setIsPlaying(false)}
              className="hidden"
            />
            <div className="flex flex-col gap-4">
              {/* 音频波形图占位 */}
              <div className="h-24 bg-gray-200 dark:bg-gray-700 rounded-lg"></div>

              {/* 控制栏 */}
              <div className="flex items-center gap-4">
                <Button variant="ghost" size="icon" onClick={handlePlayPause}>
                  {isPlaying ? <Pause size={20} /> : <Play size={20} />}
                </Button>

                <div className="text-sm">
                  {formatTime(currentTime)} / {formatTime(duration)}
                </div>

                <div className="flex-1">
                  <Slider
                    value={[currentTime]}
                    min={0}
                    max={duration}
                    step={0.1}
                    onValueChange={(value) => {
                      if (mediaRef.current) {
                        mediaRef.current.currentTime = value[0]
                      }
                    }}
                  />
                </div>

                <div className="flex items-center gap-2">
                  <Button variant="ghost" size="icon" onClick={handleMuteToggle}>
                    {isMuted ? <VolumeX size={20} /> : <Volume2 size={20} />}
                  </Button>
                  <div className="w-24">
                    <Slider
                      value={[isMuted ? 0 : volume]}
                      min={0}
                      max={1}
                      step={0.1}
                      onValueChange={handleVolumeChange}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        )

      case 'image':
        return (
          <div className="relative flex items-center justify-center group h-[600px] max-h-[75vh]">
            <img
              src={url}
              alt={title || '预览图片'}
              className="max-w-full max-h-full rounded-lg"
            />
            {/* 图片工具栏 */}
            <div className="absolute bottom-0 left-0 right-0 p-4 rounded-b-lg">
              <div className="flex justify-end gap-2">
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => window.open(url, '_blank')}
                  className="text-white/60 hover:text-white"
                >
                  <Expand size={20} />
                </Button>
              </div>
            </div>
          </div>
        )

      default:
        return <div>不支持的媒体类型</div>
    }
  }

  return (
    <Dialog open={open} onOpenChange={() => onClose?.()}>
      <DialogContent className="max-w-4xl w-full h-auto">
        <DialogHeader>
          <DialogTitle>{dialogTitle}</DialogTitle>
        </DialogHeader>
        <div className="mt-4">{renderMedia()}</div>
      </DialogContent>
    </Dialog>
  )
}

// 使用示例
const MediaPreviewExample = () => {
  const [isOpen, setIsOpen] = useState(false)
  const mediaInfo = {
    type: 'video' as const,
    url: 'https://example.com/video.mp4',
    title: '示例视频',
  }

  return (
    <div>
      <Button onClick={() => setIsOpen(true)}>打开预览</Button>

      <MediaPreview open={isOpen} onClose={() => setIsOpen(false)} {...mediaInfo} />
    </div>
  )
}

export default MediaPreview
